package com.ele.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ele.pojo.ResponseData;
import com.ele.pojo.User;
import com.ele.service.UserService;
import com.ele.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
* @author 28444
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-04-09 18:40:33
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public ResponseData<Void> userRegister(User user) {
        ResponseData<Void> responseData = new ResponseData<>();
        user.setPassword(MD5.create().digestHex(user.getPassword()));
        user.setDelTag(1);
        user.setRegTime(new Date());
        // 由于用户的主键需要程序生成，可以借助UUID完成，商业级项目，建议使用雪花算法
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        boolean save = this.save(user);
        if (save){
            responseData.setCode(20000);
            responseData.setMessage("注册成功");
            return responseData;
        }else{
            responseData.setCode(50000);
            responseData.setMessage("注册失败");
        }
        return responseData;
    }

    @Override
    public ResponseData<User> userLogin(String username, String password) {
        ResponseData<User> responseData = new ResponseData<>();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        password = MD5.create().digestHex(password);
        wrapper.eq(User::getUsername,username)
                .eq(User::getPassword,password);
        User user = this.getOne(wrapper);
        if (user != null){
            responseData.setCode(20000);
            responseData.setMessage("登录成功");
            responseData.setData(user);
        }else{
            responseData.setCode(50000);
            responseData.setMessage("登录失败");
        }
        return responseData;
    }
}